<template>
  <div class="profile-page">
    <h1>个人信息</h1>
    <el-button type="primary" @click="enableEdit">修改个人信息</el-button>
    <div class="profile-container">
      <div class="avatar-container">
        <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :file-list="fileList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleUploadSuccess"
        >
          <template #default>
            <el-icon v-if="fileList.length === 0"><FolderAdd /></el-icon>
          </template>
          <template #file="{ file }">
            <img v-if="file && file.url" class="el-upload-list__item-thumbnail" :src="file.url" alt="">
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <el-icon><ZoomIn /></el-icon>
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                <el-icon><Download /></el-icon>
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                <el-icon><Delete /></el-icon>
              </span>
            </span>
          </template>
        </el-upload>
        <el-dialog :model-value="dialogVisible" @close="dialogVisible = false">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <div v-if="fileList.length === 0" class="button-container">
          <el-button type="primary" @click="saveFiles">保存</el-button>
        </div>
      </div>
      <div class="info-container">
        <div class="info-item" v-for="field in fields" :key="field.key">
          <el-form-item :label="field.label">
            <div class="field-container">
              <el-input v-if="field.editing" v-model="field.value" :type="field.type"></el-input>
              <span v-else>{{ field.value }}</span>
              <el-button v-if="isEditing" @click="toggleEdit(field)">
                {{ field.editing ? '保存' : '修改' }}
              </el-button>
            </div>
          </el-form-item>
        </div>
      </div>
      <div class="button-container" v-if="tempFileList.length > 0">
        <el-button type="primary" @click="saveFiles">保存</el-button>
        <el-button @click="cancelFiles">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { ElAvatar, ElFormItem, ElInput, ElButton, ElUpload, ElDialog, ElMessage, ElIcon } from 'element-plus';
import { FolderAdd, ZoomIn, Download, Delete } from '@element-plus/icons-vue';
import axios from 'axios';

export default {
  name: 'ProfilePage',
  components: {
    ElAvatar,
    ElFormItem,
    ElInput,
    ElButton,
    ElUpload,
    ElDialog,
    ElIcon,
    FolderAdd,
    ZoomIn,
    Download,
    Delete
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      avatarUrl: '',
      isEditing: false,
      userId: this.$store.state.id, // 从store中获取用户ID
      fileList: this.loadFileList(), // 从本地存储加载文件列表
      tempFileList: [], // 临时文件列表
      fields: [
        { key: 'name', label: '姓名', value: '', editing: false, type: 'text' },
        { key: 'gender', label: '性别', value: '', editing: false, type: 'text' },
        { key: 'age', label: '年龄', value: '', editing: false, type: 'number' }
      ]
    };
  },
  methods: {
    enableEdit() {
      this.isEditing = !this.isEditing;
    },
    toggleEdit(field) {
      if (field.editing) {
        this.saveField(field);
      } else {
        this.editField(field);
      }
    },
    editField(field) {
      field.editing = true;
    },
    getField() {
      axios.get(`http://localhost:8085/getPatientById?id=${this.userId}`).then(response => {
        const data = response.data.data;
        this.fields.forEach(field => {
          field.value = data[field.key];
        });
      });
    },
    saveField(field) {
      field.editing = false;
      const new_data = {
        userId: this.userId,
        name: this.fields.find(f => f.key === 'name').value,
        gender: this.fields.find(f => f.key === 'gender').value === '男' ? 1 : 0,
        age: this.fields.find(f => f.key === 'age').value
      };
      axios.put('http://localhost:8085/updatePatient', new_data).then(response => {
        if (response.data.code === 1) {
          ElMessage.success('修改成功');
        } else {
          ElMessage.error('修改失败');
        }
      });
    },
    handlePictureCardPreview(file) {
      if (file && file.url) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter(f => f.uid !== file.uid);
      this.tempFileList = this.tempFileList.filter(f => f.uid !== file.uid);
      this.saveFileList();
    },
    handleDownload(file) {
      const link = document.createElement('a');
      link.href = file.url;
      link.download = file.name;
      link.click();
    },
    handleUploadSuccess(response, file, fileList) {
      file.url = URL.createObjectURL(file.raw);
      this.tempFileList.push(file);
    },
    saveFiles() {
      this.fileList = [...this.fileList, ...this.tempFileList];
      this.tempFileList = [];
      this.saveFileList();
      this.fileList = this.loadFileList();
    },
    cancelFiles() {
      this.tempFileList = [];
    },
    saveFileList() {
      localStorage.setItem(`uploadedFiles_${this.userId}`, JSON.stringify(this.fileList));
    },
    loadFileList() {
      const files = localStorage.getItem(`uploadedFiles_${this.userId}`);
      return files ? JSON.parse(files) : [];
    }
  },
  mounted() {
    this.getField(); // 在组件挂载时获取用户数据
    this.fileList = this.loadFileList(); // 在组件挂载时从本地存储加载文件列表
  }
}
</script>

<style scoped>
.profile-page {
  padding: 20px;
}

.profile-container {
  display: flex;
  align-items: flex-start;
}

.avatar-container {
  flex: 3;
  margin-right: 20px;
  position: relative;
}

.info-container {
  flex: 2;
}

.info-item {
  margin-bottom: 20px;
}

.field-container {
  display: flex;
  align-items: center;
}

.field-container .el-input,
.field-container span {
  flex: 1;
  margin-right: 10px;
}

.button-container {
  margin-top: 20px;
}
</style>
